/*
 * @(#)PayFileBean.java       2011-7-21
 *
 * Copyright（c）2010 北京云狐软件有限公司保留所有权利.
 */
package com.yunhoo.pay.bean;

import com.yunhoo.asset.util.PayCodeConstants;
import com.yunhoo.base.db.impl.PersonImpl;
import com.yunhoo.base.model.Department;
import com.yunhoo.base.model.Person;
import com.yunhoo.pay.model.Expense;
import com.yunhoo.pay.model.PayFile;
import com.yunhoo.pay.model.PayFileDetail;
import com.yunhoo.pay.model.QueryVouchers;
import com.yunhoo.pay.util.ToolsMethed;
import com.yunhoo.sys.db.util.IbatisTemplate;
import com.yunhoo.sys.util.common.LoginParam;
import com.yunhoo.sys.util.common.NavigationTool;
import com.yunhoo.sys.util.common.ToolKit;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFooter;
import org.apache.poi.hssf.usermodel.HSSFHeader;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.richfaces.component.UIDataTable;

/**
 * 类
 * <code>PayFileBean</code>
 *
 * @author 胡开龙
 * @version 2011-7-21
 * @see java.lang.Class
 * @since jdk1.6
 */
@ManagedBean(name = "payfile")
@SessionScoped
public class PayFileBean {

    private List<Expense> payfilelist = new ArrayList<Expense>();//
    private List<Expense> payfilelistForConfirm = new ArrayList<Expense>();//
    private Set<String> psns = new HashSet<String>();//
    private List<PayFile> li = new ArrayList<PayFile>();
    private String ticketcode = "";
    private String memo = "";
    private PayFile pf = new PayFile();
    private List<PayFile> payfile = new ArrayList<PayFile>();
    private DataModel model = new ListDataModel();
    private List<PayFileDetail> paydetail = new ArrayList<PayFileDetail>();
    private PayFileDetail pfd = new PayFileDetail(); //文件支付明细
    private List<PayFileDetail> filedetail = new ArrayList<PayFileDetail>();
    private List<PayFileDetail> psnfiledetail = new ArrayList<PayFileDetail>();
    private UIDataTable rowData;
    private DataModel fileDetailModel = new ListDataModel();
    private int peopletime = 0;//人次数
    private QueryVouchers qlb = new QueryVouchers();
    private List<String> voutypes = new ArrayList();
    private List<Department> deptlist = new ArrayList<Department>();
    private static String nameSpace = "file.";

    public PayFileBean() {
        //payfilelist = IbatisTemplate.queryForList("queryPayFileForChoose", null);
        //payfile = IbatisTemplate.queryForList("selectpayfile", null);
        initDeptList();
    }

    public final void initDeptList() {
        deptlist = IbatisTemplate.queryForList("department.queryAll", new Department(true));
    }

    public void selectPayFile() {
        payfile = IbatisTemplate.queryForList(nameSpace + "selectpayfile", curOrgCode().trim());
        model.setWrappedData(payfile);
    }

    public void goback() {
        NavigationTool.getSelectedUrl("/page/pay/payment/payfile/choosepay.xhtml");
    }

    //选择  生成
    public void GenerateForConfirm() {
        psns.clear();
        payfilelistForConfirm = new ArrayList();
        for (Expense e : payfilelist) {
            if (e.isSelected()) {
                payfilelistForConfirm.add(e);
                if (e.getRemain() != null && e.getRemain() != 0.0) {
                    e.setPayaccount(e.getRemain());
                } else {
                    e.setPayaccount(e.getCheckaccount());
                    e.setRemain(e.getCheckaccount());
                }
                psns.add(e.getUser().getCpsn_number().trim());
            }
            e.setSelected(false);
        }

        payfilelist = new ArrayList();
        if (psns.size() > 0 && psns != null) {
            NavigationTool.getSelectedUrl("/page/pay/payment/payfile/confirmpay.xhtml");
        } else {
            ToolKit.msgs_err("您还没有选择要生成的记录!");
        }
    }

    //确认
    public void ConfirmPay() {
        li.clear();
        for (String cpsn_num : psns) {
            Double d = 0d;
            PayFile pfs = new PayFile();
            for (int i = 0; i < payfilelistForConfirm.size(); i++) {
                if (payfilelistForConfirm.get(i).getUser().getCpsn_number().trim().equals(cpsn_num)) {
                    //System.out.println("Payed:" + payfilelistForConfirm.get(i).getPayaccount());
                    d += payfilelistForConfirm.get(i).getPayaccount();  //支付金额
                }
                payfilelistForConfirm.get(i).setPayaccount(payfilelistForConfirm.get(i).getPayaccount());

                payfilelistForConfirm.get(i).setTicketcode(ticketcode);
                payfilelistForConfirm.get(i).setMark("（标注）");
                payfilelistForConfirm.get(i).setPayDate(new Date());
                IbatisTemplate.update(nameSpace + "updatePayaccount", payfilelistForConfirm.get(i));
            }
            Person p = PersonImpl.queryByPerNumber(cpsn_num);   // 包含 姓名 帐号
            pfs.setUser(p);
            pfs.setPayaccount(d);
            li.add(pfs);
        }
        psns.clear();//?

        //插入支付文件明细表
        String peopleName = null;
        String peopleAccount = null;
        Double a = 0d;
        for (int i = 0; i < payfilelistForConfirm.size(); i++) {
            PayFileDetail pfd = new PayFileDetail();
            a = payfilelistForConfirm.get(i).getPayaccount();
            peopleName = payfilelistForConfirm.get(i).getUser().getCpsn_name();
            pfd.setPayamount(a);
            pfd.setVounumber(ToolsMethed.getPayFileMaxNumber());
            pfd.setPdate(new Date());
            pfd.setName(peopleName);
            pfd.setOrgCode(curOrgCode().trim());
            for (int j = 0; j < li.size(); j++) {
                if (li.get(j).getUser().getCpsn_number().trim().equals(payfilelistForConfirm.get(i).getUser().getCpsn_number().trim())) {
                    peopleAccount = li.get(j).getUser().getBankAccount();
                    pfd.setAccount(peopleAccount);
                    //System.out.println("accountpeople: " + peopleAccount);
                    //System.out.println("account: " + pfd.getAccount());
                }
            }
            IbatisTemplate.insert(nameSpace + "insertpayfiledetail", pfd);
        }
        GeneratePayFileList();
        //payfilelist = IbatisTemplate.queryForList("queryPayFileForChoose", null);
        NavigationTool.getSelectedUrl("/page/pay/payment/payfile/showpay.xhtml");
    }
//生成 输出

    public void GeneratePayFileList() {
        pf.setVounumber(ToolsMethed.getPayFileMaxNumber());  //
        Double amount = 0d;
        peopletime = payfilelistForConfirm.size();
        for (int i = 0; i < payfilelistForConfirm.size(); i++) {
            amount += payfilelistForConfirm.get(i).getPayaccount();
        }
        pf.setAmount(amount);
        pf.setChecknum(ticketcode);
        pf.setPdate(new Date());   //
        pf.setMemo(memo);
        pf.setCasher(curPerNum().trim());
        pf.setOrgCode(curOrgCode().trim());
        IbatisTemplate.insert(nameSpace + "insertpayfile", pf);
        payfile = IbatisTemplate.queryForList(nameSpace + "selectpayfile", curOrgCode().trim());
        model.setWrappedData(payfile);
        //li.clear();
        payfilelistForConfirm.clear();
        ticketcode = "";
        memo = "";
        //NavigationTool.getSelectedUrl("/reports/pay/querypayfile.xhtml");
        //FacesContext.getCurrentInstance().renderResponse();
        //return "main";
    }
    //展示文件支付明细

    public void showFilesDetail() {
        //PayFile pfile = (PayFile) rowData.getRowData();
        PayFile pfile = (PayFile) model.getRowData();
        Map map = new HashMap();
        map.put("vounumber", pfile.getVounumber().trim());
        map.put("orgCode", curOrgCode().trim());
        filedetail = (List<PayFileDetail>) IbatisTemplate.queryForList(nameSpace + "selectpayfileDetailByVouNumber", map);
        fileDetailModel.setWrappedData(filedetail);
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void getPsnFilesDetail() {
        //PayFile pfile = (PayFile) rowData.getRowData();
        PayFile pfile = (PayFile) model.getRowData();
        Map map = new HashMap();
        map.put("vounumber", pfile.getVounumber().trim());
        map.put("orgCode", curOrgCode().trim());
        psnfiledetail = (List<PayFileDetail>) IbatisTemplate.queryForList(nameSpace + "getPsnFileDetailByVouNumber", map);
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void expPayFile() {
        HSSFWorkbook demoWorkBook = new HSSFWorkbook();
        HSSFSheet demoSheet = demoWorkBook.createSheet("支付文件清单");
        String[] excelColumns = payFileHeader();
        List<PayFile> rows = li;

        HSSFHeader header = demoSheet.getHeader();
        header.setCenter("支付文件清单");
        HSSFRow headerRow = demoSheet.createRow(0);
        for (int i = 0; i < excelColumns.length; i++) {
            HSSFCell headerCell = headerRow.createCell((short) i);
            //headerCell.setEncoding(HSSFCell.ENCODING_UTF_16);
            headerCell.setCellValue(excelColumns[i]);
        }
        //填充数据
        int rowIndex = 1;
        for (PayFile row : rows) {
            createPayFileRow(demoWorkBook, demoSheet, row, rowIndex);
            rowIndex++;
        }
        exportExcel(demoWorkBook, demoSheet);
    }

    public void expPsnPayFile() {
        getPsnFilesDetail();
        HSSFWorkbook demoWorkBook = new HSSFWorkbook();
        HSSFSheet demoSheet = demoWorkBook.createSheet("支付文件清单");
        String[] excelColumns = payFileHeader();
        List<PayFileDetail> rows = psnfiledetail;

        HSSFHeader header = demoSheet.getHeader();
        header.setCenter("支付文件清单");
        HSSFRow headerRow = demoSheet.createRow(0);
        for (int i = 0; i < excelColumns.length; i++) {
            HSSFCell headerCell = headerRow.createCell((short) i);
            //headerCell.setEncoding(HSSFCell.ENCODING_UTF_16);
            headerCell.setCellValue(excelColumns[i]);
        }
        //填充数据
        int rowIndex = 1;
        for (PayFileDetail row : rows) {
            createPsnPayFileRow(demoWorkBook, demoSheet, row, rowIndex);
            rowIndex++;
        }
        exportExcel(demoWorkBook, demoSheet);
    }

    public void exportExcel() {
        HSSFWorkbook demoWorkBook = new HSSFWorkbook();
        HSSFSheet demoSheet = demoWorkBook.createSheet("支付文件明细表");
        String[] excelColumns = initTabeleHeader();
        List<PayFile> rows = payfile;

        HSSFHeader header = demoSheet.getHeader();
        header.setCenter("支付文件明细表");
        HSSFRow headerRow = demoSheet.createRow(0);
        for (int i = 0; i < excelColumns.length; i++) {
            HSSFCell headerCell = headerRow.createCell((short) i);
            //headerCell.setEncoding(HSSFCell.ENCODING_UTF_16);
            headerCell.setCellValue(excelColumns[i]);
        }
        //填充数据
        int rowIndex = 1;
        for (PayFile row : rows) {
            createTableRow(demoWorkBook, demoSheet, row, rowIndex);
            rowIndex++;
        }
        exportExcel(demoWorkBook, demoSheet);
    }
    //初始化表头信息

    public String[] initTabeleHeader() {
        String[] excelColumns = {"支付文件号", "支付文件日期", "总金额", "出纳", "备注"};
        return excelColumns;
    }
    //支付文件表头

    public String[] payFileHeader() {
        String[] excelColumns = {"姓名", "金额", "账户"};
        return excelColumns;
    }

    public static void createTableRow(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet, PayFile pfl, int rowIndex) {
        //创建第rowIndex行
        CreationHelper createHelper = demoWorkBook.getCreationHelper();
        HSSFCellStyle dstyle = demoWorkBook.createCellStyle();
        dstyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd"));//格式

        HSSFCell cell = null;
        HSSFRow row = demoSheet.createRow(rowIndex);
        cell = row.createCell(0);
        cell.setCellValue(PayCodeConstants.convertString(pfl.getVounumber()));
        cell = row.createCell(1);
        cell.setCellValue(PayCodeConstants.convertDate(pfl.getPdate()));
        cell.setCellStyle(dstyle);
        cell = row.createCell(2);
        cell.setCellValue(PayCodeConstants.convertDouble(pfl.getAmount()));
        cell = row.createCell(3);
        cell.setCellValue(PayCodeConstants.convertString(pfl.getCasher()));
        cell = row.createCell(4);
        cell.setCellValue(PayCodeConstants.convertString(pfl.getMemo()));
    }

    public static void createPayFileRow(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet, PayFile pfl, int rowIndex) {
        //创建第rowIndex行      
        HSSFCell cell = null;
        HSSFRow row = demoSheet.createRow(rowIndex);
        cell = row.createCell(0);
        cell.setCellValue(PayCodeConstants.convertString(pfl.getUser().getCpsn_name()));

        cell = row.createCell(1);
        cell.setCellValue(PayCodeConstants.convertDouble(pfl.getPayaccount()));
        cell = row.createCell(2);
        cell.setCellValue(PayCodeConstants.convertString(pfl.getUser().getBankAccount()));
    }

    public static void createPsnPayFileRow(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet, PayFileDetail pfl, int rowIndex) {
        //创建第rowIndex行
        HSSFCell cell = null;
        HSSFRow row = demoSheet.createRow(rowIndex);
        cell = row.createCell(0);
        cell.setCellValue(PayCodeConstants.convertString(pfl.getName()));

        cell = row.createCell(1);
        cell.setCellValue(PayCodeConstants.convertDouble(pfl.getPayamount()));
        cell = row.createCell(2);
        cell.setCellValue(PayCodeConstants.convertString(pfl.getAccount()));
    }

    public static void exportExcel(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet) {
        try {
            String strfileName = "book.xls";
            FileOutputStream fos = null;
            //导出
            demoSheet.setGridsPrinted(true);//demoSheet
            HSSFFooter footer = demoSheet.getFooter();
            footer.setRight("Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages());
            // 获得JSF上下文环境
            FacesContext context = FacesContext.getCurrentInstance();
            // 获得ServletContext对象
            ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
            // 取得文件的绝对路径
            String excelName = servletContext.getRealPath("/upload") + "/" + strfileName;//strfileName
            File exportFile = new File(excelName);
            fos = new FileOutputStream(exportFile);//fos
            demoWorkBook.write(fos);//demoWorkBook
            fos.close();

            FacesContext ctx = FacesContext.getCurrentInstance();
            ctx.responseComplete();
            HttpServletResponse httpServletResponse = (HttpServletResponse) ctx.getExternalContext().getResponse();
            ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
            httpServletResponse.setHeader("Content-disposition", "attachment; filename=" + strfileName);//strfileName
            httpServletResponse.setContentLength((int) exportFile.length());//exportFile
            httpServletResponse.setContentType("application/x-download");
            //httpServletResponse.setContentType("application/vnd.ms-excel");
            byte[] b = new byte[1024];
            int i = 0;
            FileInputStream fis = new java.io.FileInputStream(exportFile);
            while ((i = fis.read(b)) > 0) {
                servletOutputStream.write(b, 0, i);
            }
            servletOutputStream.flush();
            ctx.responseComplete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void refresh() {
        String inParam = "";
        String str = "";
        for (String type : voutypes) {
            inParam += type + ",";
        }
        if (!inParam.isEmpty()) {
            inParam = inParam.substring(0, inParam.length() - 1);
        }

        for (Department f : deptlist) {
            if (f.isSelected()) {
                str += f.getCode() + ",";
            }
        }
        if (!inParam.isEmpty() && !str.isEmpty()) {
            str = str.substring(0, str.length() - 1);
        }
        Map map = new HashMap();
        map.put("orgCode", curOrgCode().trim());
        map.put("numDateStart", qlb.getNumDateStart());
        map.put("numDateEnd", qlb.getNumDateEnd());
        map.put("typeList", inParam.trim());
        map.put("deptList", str.trim());
        map.put("checkaccountStart", qlb.getCheckaccountStart());
        map.put("checkaccountEnd", qlb.getCheckaccountEnd());
        map.put("isCashPay", qlb.isCashPay());
        map.put("perName", qlb.getPerName());
        payfilelist = IbatisTemplate.queryForList(nameSpace + "queryPayFileForChoose", map);
    }

    public List<Expense> getPayfilelistForConfirm() {
        return payfilelistForConfirm;
    }

    public void setPayfilelistForConfirm(List<Expense> payfilelistForConfirm) {
        this.payfilelistForConfirm = payfilelistForConfirm;
    }

    public List<PayFile> getLi() {
        return li;
    }

    public void setLi(List<PayFile> li) {
        this.li = li;
    }

    public String getTicketcode() {
        return ticketcode;
    }

    public void setTicketcode(String ticketcode) {
        this.ticketcode = ticketcode;
    }

    public String getMemo() {
        return memo;
    }

    public void setMemo(String memo) {
        this.memo = memo;
    }

    public List<PayFile> getPayfile() {
        return payfile;
    }

    public void setPayfile(List<PayFile> payfile) {
        this.payfile = payfile;
    }

    public List<PayFileDetail> getPaydetail() {
        return paydetail;
    }

    public void setPaydetail(List<PayFileDetail> paydetail) {
        this.paydetail = paydetail;
    }

    public PayFile getPf() {
        return pf;
    }

    public void setPf(PayFile pf) {
        this.pf = pf;
    }

    public Set<String> getPsns() {
        return psns;
    }

    public void setPsns(Set<String> psns) {
        this.psns = psns;
    }

    public PayFileDetail getPfd() {
        return pfd;
    }

    public void setPfd(PayFileDetail pfd) {
        this.pfd = pfd;
    }

    public List<PayFileDetail> getFiledetail() {
        return filedetail;
    }

    public void setFiledetail(List<PayFileDetail> filedetail) {
        this.filedetail = filedetail;
    }

    public UIDataTable getRowData() {
        return rowData;
    }

    public void setRowData(UIDataTable rowData) {
        this.rowData = rowData;
    }

    public DataModel getFileDetailModel() {
        return fileDetailModel;
    }

    public void setFileDetailModel(DataModel fileDetailModel) {
        this.fileDetailModel = fileDetailModel;
    }

    public List<PayFileDetail> getPsnfiledetail() {
        return psnfiledetail;
    }

    public void setPsnfiledetail(List<PayFileDetail> psnfiledetail) {
        this.psnfiledetail = psnfiledetail;
    }

    public int getPeopletime() {
        return peopletime;
    }

    public void setPeopletime(int peopletime) {
        this.peopletime = peopletime;
    }

    public QueryVouchers getQlb() {
        return qlb;
    }

    public void setQlb(QueryVouchers qlb) {
        this.qlb = qlb;
    }

    public List<String> getVoutypes() {
        return voutypes;
    }

    public void setVoutypes(List<String> voutypes) {
        this.voutypes = voutypes;
    }

    public List<Department> getDeptlist() {
        return deptlist;
    }

    public void setDeptlist(List<Department> deptlist) {
        this.deptlist = deptlist;
    }

    public DataModel getModel() {
        return model;
    }

    public void setModel(DataModel model) {
        this.model = model;
    }
    //

    private String curPerNum() {
        return LoginParam.getPer().getCpsn_number();
    }

    private String curPerName() {
        return LoginParam.getPer().getCpsn_name();
    }

    private String curDeptCode() {
        return LoginParam.getDept().getCode();
    }

    private String curDeptName() {
        return LoginParam.getDept().getName();
    }

    private Date curLoginDate() {
        return LoginParam.getLoginDate();
    }

    private Integer curIyear() {
        return LoginParam.getIyear();
    }

    private String curOrgCode() {
        return LoginParam.getOrg().getCode();
    }

    private String curPerRole() {
        return LoginParam.getPer().getRole();
    }

    public static String getNameSpace() {
        return nameSpace;
    }

    public static void setNameSpace(String nameSpace) {
        PayFileBean.nameSpace = nameSpace;
    }

    public List<Expense> getPayfilelist() {
        return payfilelist;
    }

    public void setPayfilelist(List<Expense> payfilelist) {
        this.payfilelist = payfilelist;
    }
}
